#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

void swap1(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}


void Adjustdown(int* p, int n, int parent)
{
	int minchilen = parent * 2 + 1;
	while (minchilen < n)
	{
		if (minchilen + 1 < n && p[minchilen] > p[minchilen + 1])
		{
			minchilen++;
		}
		if (p[parent] > p[minchilen])
		{
			swap1(&p[parent], &p[minchilen]);
			parent = minchilen;
			minchilen = parent * 2 + 1;
		}
		else
			break;
	}
}


creatdatafile(const char* p, int n)
{
	FILE* fu = fopen(p, "w");
	if (fu == NULL)
	{
		perror("fu error");
		exit(-1);
	}
	srand(time(0));
	for (int i = 0; i < n; i++)
	{
		fprintf(fu, "%d\n", rand() % 1000000);
	}
	fclose(p);
}

void PrintTopK(const char* p, int k)
{
	FILE* fu = fopen(p, "r");
	if (fu == NULL)
	{
		perror("fu error");
		exit(-1);
	}
	int* tmp = (int*)malloc(sizeof(int) * k);
	for (int i = 0; i < k; i++)
	{
		fscanf(fu, "%d\n", &tmp[i]);
	}
	for (int i = (k - 1 - 1) / 2; i >= 0; i--)
	{
		Adjustdown(tmp, k, i);
	}
	int val = 0;
	while (fscanf(fu, "%d\n", &val) != EOF)
	{
		if (val > tmp[0])
		{
			tmp[0] = val;
			Adjustdown(tmp, k, 0);
		}
	}
	for (int i = 0; i < k; i++)
	{
		printf("%d ", tmp[i]);
	}
}

int main()
{
	const char* filename = "data.txt";
	int N = 10000;
	int K = 10;
	//creatdatafile(filename,N);
	PrintTopK(filename, K);
	return 0;
}